package leetCode203;

import java.util.Objects;

public class main {
    public static void main(String[] args) {
        // 创建链表: 1 -> 2 -> 6 -> 3 -> 4 -> 5 -> 6
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(6);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next.next = new ListNode(6);

        // 打印原始链表
        System.out.println("原始链表:");
        printList(head);

        // 删除值为6的节点
        int valToRemove = 6;
        ListNode result = removeElements(head, valToRemove);

        // 打印删除后的链表
        System.out.println("删除值为 " + valToRemove + " 后的链表:");
        printList(result);
    }

    public static ListNode removeElements(ListNode head, int val) {
        // 移除头部相同元素的节点
        while(head!=null && head.val==val) {
            head = head.next;
        }

        // 临时节点
        ListNode curr = head;
        while(curr!=null && curr.next !=null) {
            if(curr.next.val == val){
                curr.next = curr.next.next;
            } else {
                curr = curr.next;
            }
        }

        return head;
    }

    public static ListNode removeElements2(ListNode head, int val) {
        // 临时对象
        ListNode cur = head;
        while (Objects.nonNull(cur) && Objects.nonNull(cur.next)) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;
            } else {
              cur = cur.next;
            }

        }

        return head;
    }

    // 辅助方法：打印链表
    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
